﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using Microhard.Framework.MVCHelper;
using Microhard.Permission.Interface;
using Microhard.Core;
using Microhard.Permission.Models;
using Microhard.Core.DBUtility;


namespace Microhard.Permission.MVCFilter
{
    public class MVCFilterAtrForDataPermission : ActionFilterAttribute, Microhard.Permission.MVCFilter.IMvcFilter
    {
        private IDataCollectionAuthorization ica = IoC.Resolve<IDataCollectionAuthorization>();
        private IDataPermission id = IoC.Resolve<IDataPermission>();
        private IUser user = IoC.Resolve<IUser>();

        private string _onExecutingFilterDataType;
        private string _onExecutedFilterDataType;
        private string _dataScopeactionParameterName = "scope";

        /// <summary>
        /// 接收数据权限结果的参数名称
        /// </summary>
        public string DataScopeactionParameterName
        {
            set
            {
                this._dataScopeactionParameterName = value;
            }
            get
            {
                return this._dataScopeactionParameterName;
            }
        }
        /// <summary>
        /// 在OnExecuting时使用的数据过滤器
        /// </summary>
        public string OnExecutingFilterDataType
        {
            set { this._onExecutingFilterDataType = value; }
            get
            {
                return this._onExecutingFilterDataType;
            }
        }
        /// <summary>
        /// 在OnExecuted时使用的数据过滤器
        /// </summary>
        public string OnExecutedFilterDataType
        {
            set { this._onExecutedFilterDataType = value; }
            get
            {
                return this._onExecutedFilterDataType;
            }
        }

        public MVCFilterAtrForDataPermission()
        {
            //表示作为action filter第三个执行
            this.Order = 2;
        }


        #region IMvcFilter Members

        public void RedirectToPage(ActionExecutingContext filterContext)
        {
            string msg = "您对此数据没有访问权限，请向管理员申请";
            user.SignOut();
            filterContext.HttpContext.Session.Clear();
            if (filterContext.RequestContext.HttpContext.Request.IsAjaxRequest())
            {
                filterContext.Result = new JsonResult()
                {
                    Data = msg
                };
            }
            else
            {
                var ad = new ViewResult();
                ad.ViewName = "NeedDataPermission";
                filterContext.Result = ad;
            }
        }

        #endregion

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            User currentUser = MVCFilterAtrForLogon.GetLogonUser();
            if (currentUser == null)
                return;
            bool isAdminAction = false;
            if (FilterHelper.IsSysAdminAction(filterContext.ActionDescriptor.ControllerDescriptor.ControllerName.ToLower()))
            {
                isAdminAction = true;
            }
            var currentPims = filterContext.HttpContext.Items[SysConst.DATACOLLECTION_PERMISSIONID] as List<Microhard.Permission.Models.Permission>;
            string actionName = filterContext.ActionDescriptor.ActionName.ToLower();

            //传入拥有的数据权限,admin模块不进行验证,注:FluentValidation的验证发生在Model binding时期。此时的model已经
            //被验证过
            var dataScope = ica.GetDataScope(currentPims.First().ResID, currentUser);
            //从之前的scope 中取出，并将员工信息赋予到现在的scope中
            if (filterContext.ActionParameters.Keys.Contains(this._dataScopeactionParameterName))
            {
                var scope = filterContext.ActionParameters[this._dataScopeactionParameterName] as ScopeResult;
                if (scope != null)
                {
                    dataScope.CurrentUserRealName = scope.CurrentUserRealName;
                    dataScope.CurrentUserRoleNames = scope.CurrentUserRoleNames;
                    dataScope.EmpInfo = scope.EmpInfo;
                }
            }
            filterContext.ActionParameters[this._dataScopeactionParameterName] = dataScope;
            //为页面获得scope而设置
            filterContext.Controller.ViewData["scope"] = dataScope;
            //数据权限验证
            bool IsWorkflowAction = false;
            if (string.IsNullOrEmpty(this._onExecutingFilterDataType))
            {
                this._onExecutingFilterDataType = actionName;
            }
            IActionDataFilter acFilter = ActionFilterFactory.GetActionFilter(this._onExecutingFilterDataType, out IsWorkflowAction);
            acFilter.IsAdminAction = isAdminAction;
            //无数据权限访问，则跳转到禁止页面
            if (!acFilter.FilterAction(filterContext, currentUser, currentPims, dataScope))
            {
                this.RedirectToPage(filterContext);
                return;
            }
            else
            {
                //如果一个action被连续调用多次，则需要判断。
                if (!filterContext.HttpContext.Items.Contains("acFilter"))
                {
                    filterContext.HttpContext.Items.Add("acFilter", acFilter);
                }
            }
        }

        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            //admin不做数据权限判断
            if (FilterHelper.IsSysAdminAction(filterContext.ActionDescriptor.ControllerDescriptor.ControllerName))
            {
                return;
            }
            string actionName = filterContext.ActionDescriptor.ActionName.ToLower();
            var currentUser = MVCFilterAtrForLogon.GetLogonUser();
            if (currentUser != null)
            {
                if (string.IsNullOrEmpty(this._onExecutedFilterDataType))
                {
                    this._onExecutedFilterDataType = actionName;
                }
                IAfterActionDataFilter filter = ActionFilterFactory.GetActionExecutedFilter(this._onExecutedFilterDataType.ToLower());
                if (filter != null)
                {
                    filter.DataPermission = id;
                    if (filter != null)
                    {
                        filter.FilterAction(filterContext, currentUser);
                    }
                }
            }
        }
    }
}
